package com.example.casper.Experiment2024;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageDecoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.casper.Experiment2024.data.DataBank;
import com.example.casper.Experiment2024.data.TravelRecord;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class TravelRecordListFragment extends Fragment {

    private static ArrayList<TravelRecord> records;
    private ActivityResultLauncher<Intent> launcherAdd;
    private ActivityResultLauncher<Intent> launcherUpdate;
    private ShopItemAdapter recordItemAdapter;

    public TravelRecordListFragment(){}


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_travel_record_list, container, false);

        RecyclerView mainRecyclerView = rootView.findViewById(R.id.recycler_view_the_records);
        mainRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        // 获取添加按钮实例并添加点击监听器
        Button buttonAdd = rootView.findViewById(R.id.button_add);
        buttonAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intentAdd = new Intent(getContext(), TravelRecordDetailsActivity.class);
                launcherAdd.launch(intentAdd);
            }
        });

        // 从本地存储读取记录数据
        DataBank databank = new DataBank(getContext());
        records = databank.readTravelRecords();
        if (records.isEmpty()) {

            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.jinan_university);
            String imagePath = saveImageToInternalStorage(bitmap, "default_image");
            records.add(new TravelRecord("地点","暨南大学 ", imagePath,"2025-1-1", 22.249942,113.534341));
        }

        // 绑定适配器
        recordItemAdapter = new ShopItemAdapter(records); // 传递getContext()
        mainRecyclerView.setAdapter(recordItemAdapter);

        registerForContextMenu(mainRecyclerView);
        recordItemAdapter.notifyDataSetChanged();
        TextView emptyView = rootView.findViewById(R.id.emptyView);
        if (records.isEmpty()) {
            emptyView.setVisibility(View.VISIBLE);
            mainRecyclerView.setVisibility(View.GONE);
        } else {
            emptyView.setVisibility(View.GONE);
            mainRecyclerView.setVisibility(View.VISIBLE);
        }



        return rootView;
    }
    private class ShopItemAdapter extends RecyclerView.Adapter {
        private ArrayList<TravelRecord> records;

        public ShopItemAdapter(ArrayList<TravelRecord> records) {
            this.records = records;

        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_travel_record, parent, false);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            MyViewHolder myViewHolder=(MyViewHolder)holder;
            myViewHolder.getTextViewPositionName().setText("地名: "+records.get(position).getPositionName());
            myViewHolder.getTextViewLongitude().setText("经度: "+ records.get(position).getLongitude());
            myViewHolder.getTextViewLatitude().setText("纬度: "+ records.get(position).getLatitude());
            myViewHolder.getTextViewRecordContent().setText("详细描述："+records.get(position).getDescription());
            myViewHolder.getTextViewTime().setText("时间："+records.get(position).getTime());


            if (records.get(position).getImagePath() != null) {
                myViewHolder.imageViewPicture.setImageBitmap(BitmapFactory.decodeFile(records.get(position).getImagePath()));
            } else {
                myViewHolder.imageViewPicture.setImageResource(R.drawable.book_no_name);
            }
        }

        public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
            private final ImageView imageViewPicture;
            private final TextView textViewPositionName;
            private final TextView textViewRecordContent;
            private final TextView textViewTime;
            private final TextView textViewLongitude;
            private final TextView textViewLatitude;

            public ImageView getImageViewPicture() {
                return imageViewPicture;
            }
            ;
            public TextView getTextViewLongitude(){return textViewLongitude;};
            public TextView getTextViewLatitude(){return textViewLatitude;};

            public TextView getTextViewPositionName() {
                return textViewPositionName;
            }

            public TextView getTextViewRecordContent() {
                return textViewRecordContent;
            }

            public TextView getTextViewTime(){
                return textViewTime;
            }


            public MyViewHolder(@NonNull View itemView) {
                super(itemView);
                this.imageViewPicture = itemView.findViewById(R.id.image_view);
                this.textViewPositionName = itemView.findViewById(R.id.position_name);
                this.textViewRecordContent = itemView.findViewById(R.id.record_daka);
                this.textViewTime = itemView.findViewById(R.id.current_time);
                this.textViewLongitude=itemView.findViewById(R.id.textview_longitude);
                this.textViewLatitude=itemView.findViewById(R.id.textview_latitude);
                itemView.setOnCreateContextMenuListener(this);


            }



            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("具体操作");
                menu.add(0, 0, this.getAdapterPosition(), "删除");
                menu.add(0, 1, this.getAdapterPosition(), "修改");
            }
        }

        public int getItemCount() {
            return records.size();
        }

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        launcherAdd = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        assert data!= null;
                        String positionName = data.getStringExtra("position_name");
                        String recordContent = data.getStringExtra("record_content");
                        double longitude = data.getDoubleExtra("longitude",0);
                        double latitude = data.getDoubleExtra("latitude",0);

                        int position=data.getIntExtra("position",0);
                        // 创建SimpleDateFormat对象，指定日期格式
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        // 格式化当前时间为指定格式的字符串
                        String formattedDate = sdf.format(new Date());
                        // 获取图片 URI
                        String imageUriString = data.getStringExtra("image_path");
                        Uri imageUri = Uri.parse(imageUriString);

                        // 将 URI 转换为 Bitmap
                        Bitmap bitmap = null;
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
                            try {
                                bitmap = ImageDecoder.decodeBitmap(ImageDecoder.createSource(getContext().getContentResolver(), imageUri));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        } else {
                            try {
                                bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), imageUri);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        // 将 Bitmap 转换为 Drawable（如果需要）
                        String imagePath = saveImageToInternalStorage(bitmap,positionName); // 你需要实现这个方法来保存图片并返回资源ID

                        records.add(position,new TravelRecord(positionName,recordContent,imagePath,formattedDate,latitude,longitude));



                        recordItemAdapter.notifyItemInserted(position);
                        DataBank databank=new DataBank(this.getContext());
                        databank.saveItems(records);


                    }
                });

        launcherUpdate = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        assert data!= null;
                        String updatedPositionName = data.getStringExtra("position_name");
                        String updatedRecordContent = data.getStringExtra("record_content");
                        double longitude = data.getDoubleExtra("longitude",0);
                        double latitude = data.getDoubleExtra("latitude",0);
                        // 接收从ItemActivity返回的更新后的图片路径
                        String imagePath = data.getStringExtra("image_path");
                        int position = data.getIntExtra("position", 0);
                        TravelRecord trip = records.get(position);
                        trip.setPositionName(updatedPositionName);
                        trip.setDescription(updatedRecordContent);
                        trip.setImagePath(imagePath);
                        trip.setLongitude(longitude);
                        trip.setLatitude(latitude);
                        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);

                        recordItemAdapter.notifyItemChanged(position);
                        DataBank databank = new DataBank(getContext());
                        databank.saveItems(records);
                    }
                });
    }

    private String saveImageToInternalStorage(Bitmap bitmap, String imageName) {
        if (bitmap == null || imageName == null || imageName.isEmpty()) {
            Log.e("TravelRecordListFragment", "Bitmap or imageName is null or empty");
            return null;
        }
        // 获取应用的内部存储目录
        File directory = getContext().getFilesDir();
        File imageFile = new File(directory, imageName);

        try (FileOutputStream fos = new FileOutputStream(imageFile)) {
            // 将 Bitmap 写入文件
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
        } catch (IOException e) {
            Log.e("TravelRecordListFragment", "Error saving image to internal storage", e);
        }

        // 返回文件的绝对路径
        return imageFile.getAbsolutePath();
    }

    // 处理上下文菜单选项点击事件（用于删除和修改记录操作）
    public boolean onContextItemSelected(MenuItem itemMenu) {
        switch (itemMenu.getItemId()) {
            case 0:
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setTitle("删除数据");
                builder.setMessage("确定要删除吗?");
                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        int position = itemMenu.getOrder();
                        records.remove(position);
                        recordItemAdapter.notifyItemRemoved(position);
                        DataBank dataBank = new DataBank(getContext());
                        dataBank.saveItems(records);
                    }
                });
                builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
                break;
            case 1:
                showModifyDialog();
                break;
            default:
                return super.onContextItemSelected(itemMenu);
        }
        return true;
    }
    private void showModifyDialog() {
        String[] recordNames = new String[records.size()];
        for (int i = 0; i < records.size(); i++) {
            recordNames[i] = records.get(i).getPositionName();
        }

        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getContext());
        builder.setTitle("选择记录进行修改")
                .setItems(recordNames, (dialog, which) -> {
                    Intent intentUpdate = new Intent(getContext(), TravelRecordDetailsActivity.class);
                    TravelRecord selectedRecord = records.get(which);
                    intentUpdate.putExtra("position", which);
                    intentUpdate.putExtra("name", selectedRecord.getPositionName());
                    intentUpdate.putExtra("longitude", selectedRecord.getLongitude());
                    intentUpdate.putExtra("latitude", selectedRecord.getLatitude());
                    intentUpdate.putExtra("description", selectedRecord.getDescription());
                    intentUpdate.putExtra("image", selectedRecord.getImagePath());
                    launcherUpdate.launch(intentUpdate);
                });
        builder.show();
    }

    // 创建一个新的实例方法（可根据需要传递参数进行实例化，当前示例无额外参数）
    public static TravelRecordListFragment newInstance() {
        TravelRecordListFragment fragment = new TravelRecordListFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

}
